<?php

namespace Hilaoyu\Utils\Traits;


use Hilaoyu\Utils\UtilArr;
use Hilaoyu\Utils\UtilSupport;

trait ErrorsTrait
{
    protected $_errors_trait_errors = [];
    static protected $_errors_trait_static_errors = [];

    public function setError($msg, $key = null)
    {

        if (!empty($key) && is_string($key)) {
            $key = trim($key);
            $errors[$key] = $msg;
        } else {
            $errors = (array)$msg;
        }

        $this->_errors_trait_errors = array_merge_recursive($this->_errors_trait_errors,$errors);


        return $this;
    }

    public function ClearError($key='')
    {
        if(is_string($key) && $key){
            unset($this->_errors_trait_errors[$key]);
        }else{
            $this->_errors_trait_errors = array();
        }
    }

    public function getError($reArr = true, $clean = true)
    {
        $error = $this->_errors_trait_errors;


        if(is_string($reArr) && $reArr){
            $error = data_get($error,$reArr);
        }elseif (! $reArr) {
            $error = UtilArr::toString($error);
        }

        if ($clean) {
            $this->ClearError($reArr);
        }
        return $error;
    }


    static public function SetStaticError($msg, $key = null)
    {

        if (!empty($key) && is_string($key)) {
            $key = trim($key);
            $errors[$key] = $msg;
        } else {
            $errors = (array)$msg;
        }

        static::$_errors_trait_static_errors = array_merge_recursive(static::$_errors_trait_static_errors,$errors);


    }

    static public function ClearStaticError($key='')
    {
        if(is_string($key) && $key){
            unset(static::$_errors_trait_static_errors[$key]);
        }else{
            static::$_errors_trait_static_errors = array();
        }

    }

    static public function GetStaticError($reArr = true, $clean = true)
    {
        $error = static::$_errors_trait_static_errors;


        if(is_string($reArr) && $reArr){
            $error = data_get($error,$reArr);
        }elseif (! $reArr) {
            $error = UtilArr::toString($error);
        }

        if ($clean) {
            static::ClearStaticError($reArr);
        }
        return $error;
    }

}
